{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8b892c8",
   "metadata": {},
   "source": [
    "Printed and electronic copies of *Modeling and Simulation in Python* are available from [No Starch Press](https://nostarch.com/modeling-and-simulation-python) and [Bookshop.org](https://bookshop.org/p/books/modeling-and-simulation-in-python-allen-b-downey/17836697?ean=9781718502161) and [Amazon](https://amzn.to/3y9UxNb)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "unauthorized-winter",
   "metadata": {},
   "source": [
    "# Torque"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "imported-table",
   "metadata": {
    "tags": []
   },
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "formal-context",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://raw.githubusercontent.com/AllenDowney/' +\n",
    "         'ModSimPy/master/modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "progressive-typing",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "plastic-trigger",
   "metadata": {
    "tags": []
   },
   "source": [
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "Click here to access the notebooks: <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "chief-delight",
   "metadata": {},
   "source": [
    "In the previous chapter we modeled a system with constant angular\n",
    "velocity.\n",
    "In this chapter we take the next step, modeling a system with angular acceleration and deceleration."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "earned-motorcycle",
   "metadata": {},
   "source": [
    "## Angular Acceleration\n",
    "\n",
    "Just as linear acceleration is the derivative of velocity, *angular\n",
    "acceleration* is the derivative of angular velocity. And just as linear acceleration is caused by force, angular acceleration is caused by the rotational version of force, *torque*. If you are not familiar with torque, you can read about it at <http://modsimpy.com/torque>.\n",
    "\n",
    "In general, torque is a vector quantity, defined as the *cross\n",
    "product* of $\\vec{r}$ and $\\vec{F}$, where $\\vec{r}$ is the *lever\n",
    "arm*, a vector from the center of rotation to the point where the force is applied, and $\\vec{F}$ is the vector that represents the magnitude and direction of the force."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "promotional-trigger",
   "metadata": {},
   "source": [
    "For the problems in this chapter, however, we only need the *magnitude* of torque; we don't care about the direction. In that case, we can compute this product of scalar quantities:\n",
    "\n",
    "$$\\tau = r F \\sin \\theta$$ \n",
    "\n",
    "where $\\tau$ is torque, $r$ is the length of the lever arm, $F$ is the magnitude of force, and $\\theta$ is the angle between $\\vec{r}$ and $\\vec{F}$.\n",
    "\n",
    "Since torque is the product of a length and a force, it is expressed in newton meters (Nm)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "infrared-summit",
   "metadata": {},
   "source": [
    "## Moment of Inertia\n",
    "\n",
    "In the same way that linear acceleration is related to force by Newton's second law of motion, $F=ma$, angular acceleration is related to torque by another form of Newton's law: \n",
    "\n",
    "$$\\tau = I \\alpha$$ \n",
    "\n",
    "where $\\alpha$ is angular acceleration and $I$ is *moment of inertia*. Just as mass is what makes it hard to accelerate an object, moment of inertia is what makes it hard to spin an object.\n",
    "\n",
    "In the most general case, a 3-D object rotating around an arbitrary\n",
    "axis, moment of inertia is a *tensor*, which is a function that takes a\n",
    "vector as a parameter and returns a vector as a result.\n",
    "\n",
    "Fortunately, in a system where all rotation and torque happens around a single axis, we don't have to deal with the most general case. We can treat moment of inertia as a scalar quantity.\n",
    "\n",
    "For a small object with mass $m$, rotating around a point at distance\n",
    "$r$, the moment of inertia is $I = m r^2$. For more complex objects, we can compute $I$ by dividing the object into small masses, computing\n",
    "moments of inertia for each mass, and adding them up.\n",
    "For most simple shapes, people have already done the\n",
    "calculations; you can just look up the answers. For example, see\n",
    "<http://modsimpy.com/moment>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "julian-klein",
   "metadata": {},
   "source": [
    "## Teapots and Turntables\n",
    "\n",
    "Tables in Chinese restaurants often have a rotating tray or turntable\n",
    "that makes it easy for customers to share dishes. These turntables are\n",
    "supported by low-friction bearings that allow them to turn easily and\n",
    "glide. However, they can be heavy, especially when they are loaded with food, so they have a high moment of inertia.\n",
    "\n",
    "Suppose I am sitting at a table with a pot of tea on the turntable\n",
    "directly in front of me, and the person sitting directly opposite asks\n",
    "me to pass the tea. I push on the edge of the turntable with 2 N of\n",
    "force until it has turned 0.5 rad, then let go. The turntable glides\n",
    "until it comes to a stop 1.5 rad from the starting position. How much\n",
    "force should I apply for a second push so the teapot glides to a stop\n",
    "directly opposite me?\n",
    "\n",
    "We'll answer this question in these steps:\n",
    "\n",
    "1.  I'll use the results from the first push to estimate the coefficient of friction for the turntable.\n",
    "\n",
    "2.  As an exercise, you'll use that coefficient of friction to estimate the force needed to rotate the turntable through the remaining angle.\n",
    "\n",
    "Our simulation will use the following parameters:\n",
    "\n",
    "1.  The radius of the turntable is 0.5 m, and its weight is 7 kg.\n",
    "\n",
    "2.  The teapot weights 0.3 kg, and it sits 0.4 m from the center of the turntable.\n",
    "\n",
    "The following figure shows the scenario, where $F$ is the force I apply to the turntable at the perimeter, perpendicular to the lever arm, $r$, and $\\tau$ is the resulting torque. The  circle near the bottom is the teapot.\n",
    "\n",
    "![Diagram of a turntable with a\n",
    "teapot.](https://github.com/AllenDowney/ModSim/raw/main/figs/teapot.png)\n",
    "\n",
    "Here are the parameters from the statement of the problem:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "spiritual-disorder",
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import pi\n",
    "\n",
    "radius_disk = 0.5     # m\n",
    "mass_disk = 7         # kg\n",
    "radius_pot = 0.4      # m\n",
    "mass_pot = 0.3        # kg\n",
    "force = 2             # N\n",
    "\n",
    "theta_push = 0.5        # radian\n",
    "theta_test = 1.5        # radian\n",
    "theta_target = pi       # radian"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bound-algorithm",
   "metadata": {},
   "source": [
    "`theta_push` is the angle where I stop pushing on the turntable.\n",
    "`theta_test` is how far the table turns during my test push.\n",
    "`theta_target` is where we want the table to be after the second push.\n",
    "\n",
    "We can use these parameters to compute the moment of inertia of the turntable, using the formula for a horizontal disk revolving around a vertical axis through its center: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "recorded-administration",
   "metadata": {},
   "outputs": [],
   "source": [
    "I_disk = mass_disk * radius_disk**2 / 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "economic-concord",
   "metadata": {},
   "source": [
    "We can also compute the moment of inertia of the teapot, treating it as a point mass:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "present-termination",
   "metadata": {},
   "outputs": [],
   "source": [
    "I_pot = mass_pot * radius_pot**2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dominican-joseph",
   "metadata": {},
   "source": [
    "The total moment of inertia is the sum of these parts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "former-driver",
   "metadata": {},
   "outputs": [],
   "source": [
    "I_total = I_disk + I_pot"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "effective-danger",
   "metadata": {},
   "source": [
    "Friction in the bearings probably depends on the weight of the turntable and its contents, but probably does not depend on angular velocity.\n",
    "So we'll assume that it is a constant.\n",
    "We don't know what it is, so I will start with a guess, and we will use `root_scalar` to improve it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "enclosed-happiness",
   "metadata": {},
   "outputs": [],
   "source": [
    "torque_friction = 0.3   # N*m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "balanced-method",
   "metadata": {},
   "source": [
    "For this problem we'll treat friction as a torque.\n",
    "\n",
    "The state variables we'll use are `theta`, which is the angle of the table in rad, and `omega`, which is angular velocity in rad/s."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "passing-sullivan",
   "metadata": {},
   "outputs": [],
   "source": [
    "init = State(theta=0, omega=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "second-leather",
   "metadata": {},
   "source": [
    "Now we can make a `System` with the initial state, `init`, the maximum duration of the simulation, `t_end`, and the parameters we are going to vary, `force` and `torque_friction`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "acoustic-furniture",
   "metadata": {},
   "outputs": [],
   "source": [
    "system = System(init=init, \n",
    "                force=force,\n",
    "                torque_friction=torque_friction,\n",
    "                t_end=20)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "crucial-recognition",
   "metadata": {},
   "source": [
    "Here's a slope function that takes the current state, which contains angle and angular velocity, and returns the derivatives, angular velocity and angular acceleration:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ranking-local",
   "metadata": {},
   "outputs": [],
   "source": [
    "def slope_func(t, state, system):\n",
    "    theta, omega = state\n",
    "    force = system.force\n",
    "    torque_friction = system.torque_friction\n",
    "    \n",
    "    torque = radius_disk * force - torque_friction\n",
    "    alpha = torque / I_total\n",
    "    \n",
    "    return omega, alpha "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "exposed-court",
   "metadata": {},
   "source": [
    "In this scenario, the force I apply to the turntable is always\n",
    "perpendicular to the lever arm, so $\\sin \\theta = 1$ and the torque due\n",
    "to force is $\\tau = r F$.\n",
    "\n",
    "`torque_friction` represents the torque due to friction. Because the\n",
    "turntable is rotating in the direction of positive `theta`, friction\n",
    "acts in the direction of negative `theta`.\n",
    "\n",
    "We can test the slope function with the initial conditions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "saved-purple",
   "metadata": {},
   "outputs": [],
   "source": [
    "slope_func(0, system.init, system)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "forbidden-legislature",
   "metadata": {},
   "source": [
    "We are almost ready to run the simulation, but first there's a problem we have to address."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tribal-disclosure",
   "metadata": {},
   "source": [
    "## Two Phase Simulation\n",
    "\n",
    "When I stop pushing on the turntable, the angular acceleration changes\n",
    "abruptly. We could implement the slope function with an `if` statement\n",
    "that checks the value of `theta` and sets `force` accordingly. And for a coarse model like this one, that might be fine. But a more robust approach is to simulate the system in two phases:\n",
    "\n",
    "1.  During the first phase, force is constant, and we run until `theta` is 0.5 radians.\n",
    "\n",
    "2.  During the second phase, force is 0, and we run until `omega` is 0.\n",
    "\n",
    "Then we can combine the results of the two phases into a single\n",
    "`TimeFrame`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "decent-microwave",
   "metadata": {},
   "source": [
    "### Phase 1\n",
    "\n",
    "Here's the event function I'll use for Phase 1; it stops the simulation when `theta` reaches `theta_push`, which is when I stop pushing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "black-wichita",
   "metadata": {},
   "outputs": [],
   "source": [
    "def event_func1(t, state, system):\n",
    "    theta, omega = state\n",
    "    return theta - theta_push"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "separate-college",
   "metadata": {},
   "source": [
    "We can test it with the initial conditions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ranking-google",
   "metadata": {},
   "outputs": [],
   "source": [
    "event_func1(0, system.init, system)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "reduced-sharp",
   "metadata": {},
   "source": [
    "And run the first phase of the simulation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "meaning-philosophy",
   "metadata": {},
   "outputs": [],
   "source": [
    "results1, details1 = run_solve_ivp(system, slope_func,\n",
    "                                   events=event_func1)\n",
    "details1.message"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "spread-application",
   "metadata": {},
   "source": [
    "Here are the last few time steps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "focused-invention",
   "metadata": {},
   "outputs": [],
   "source": [
    "results1.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "willing-receipt",
   "metadata": {},
   "source": [
    "It takes a little more than a second for me to rotate the table 0.5 rad.\n",
    "When I release the table, the angular velocity is about 0.87 rad / s.\n",
    "\n",
    "Before we run the second phase, we have to extract the final time and\n",
    "state of the first phase."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "russian-experience",
   "metadata": {},
   "outputs": [],
   "source": [
    "t_2 = results1.index[-1]\n",
    "init2 = results1.iloc[-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aware-generator",
   "metadata": {},
   "source": [
    "### Phase 2\n",
    "\n",
    "Now we can make a `System` object for Phase 2 with the initial state\n",
    "from Phase 1 and with `force=0`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "chinese-cover",
   "metadata": {},
   "outputs": [],
   "source": [
    "system2 = system.set(t_0=t_2, init=init2, force=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "actual-monaco",
   "metadata": {},
   "source": [
    "For the second phase, we need an event function that stops when the\n",
    "turntable stops; that is, when angular velocity is 0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "recovered-section",
   "metadata": {},
   "outputs": [],
   "source": [
    "def event_func2(t, state, system):\n",
    "    theta, omega = state\n",
    "    return omega"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ordinary-miniature",
   "metadata": {},
   "source": [
    "We'll test it with the initial conditions for Phase 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "corporate-taste",
   "metadata": {},
   "outputs": [],
   "source": [
    "event_func2(system2.t_0, system2.init, system2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "administrative-major",
   "metadata": {},
   "source": [
    "The result is the angular velocity at the beginning of Phase 2, in rad/s.\n",
    "\n",
    "Now we can run the second phase."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "destroyed-adrian",
   "metadata": {},
   "outputs": [],
   "source": [
    "results2, details2 = run_solve_ivp(system2, slope_func,\n",
    "                                   events=event_func2)\n",
    "details2.message"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hindu-requirement",
   "metadata": {},
   "source": [
    "### Combining the Results\n",
    "\n",
    "Pandas provides a function called `concat`, which makes a \n",
    "`DataFrame` with the rows from `results1` followed by the rows from `results2`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "frank-scene",
   "metadata": {},
   "outputs": [],
   "source": [
    "results = pd.concat([results1, results2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "wooden-butterfly",
   "metadata": {},
   "source": [
    "Here are the last few time steps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "short-singer",
   "metadata": {},
   "outputs": [],
   "source": [
    "results.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "metropolitan-roommate",
   "metadata": {},
   "source": [
    "At the end, angular velocity is close to 0, and the total rotation is about 1.7 rad, a little farther than we were aiming for.\n",
    "\n",
    "We can plot `theta` for both phases."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "distributed-humanitarian",
   "metadata": {},
   "outputs": [],
   "source": [
    "results.theta.plot(label='theta')\n",
    "decorate(xlabel='Time (s)',\n",
    "             ylabel='Angle (rad)')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "excess-confidence",
   "metadata": {},
   "source": [
    "And `omega`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "proved-surfing",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "results.omega.plot(label='omega', color='C1')\n",
    "decorate(xlabel='Time (s)',\n",
    "             ylabel='Angular velocity (rad/s)')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "handy-frontier",
   "metadata": {},
   "source": [
    "Angular velocity, `omega`, increases linearly while I am pushing, and decreases linearly after I let go. The angle, `theta`, is the integral of angular velocity, so it forms a parabola during each phase.\n",
    "\n",
    "In the next section, we'll use this simulation to estimate the torque\n",
    "due to friction."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "careful-minneapolis",
   "metadata": {},
   "source": [
    "## Estimating Friction\n",
    "\n",
    "Let's take the code from the previous section and wrap it in a function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "constant-wallace",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_two_phases(force, torque_friction, system):\n",
    "    \n",
    "    # put the specified parameters into the System object\n",
    "    system1 = system.set(force=force, \n",
    "                         torque_friction=torque_friction)\n",
    "\n",
    "    # run phase 1\n",
    "    results1, details1 = run_solve_ivp(system1, slope_func, \n",
    "                                       events=event_func1)\n",
    "\n",
    "    # get the final state from phase 1\n",
    "    t_2 = results1.index[-1]\n",
    "    init2 = results1.iloc[-1]\n",
    "    \n",
    "    # run phase 2\n",
    "    system2 = system1.set(t_0=t_2, init=init2, force=0)\n",
    "    results2, details2 = run_solve_ivp(system2, slope_func, \n",
    "                                       events=event_func2)\n",
    "    \n",
    "    # combine and return the results\n",
    "    results = pd.concat([results1, results2])\n",
    "    return results"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "positive-possible",
   "metadata": {},
   "source": [
    "I'll test it with the same parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "played-ranking",
   "metadata": {},
   "outputs": [],
   "source": [
    "force = 2\n",
    "torque_friction = 0.3\n",
    "results = run_two_phases(force, torque_friction, system)\n",
    "results.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "damaged-concert",
   "metadata": {},
   "source": [
    "These results are the same as in the previous section.\n",
    "\n",
    "We can use `run_two_phases` to write an error function we can use, with `root_scalar`, to find the torque due to friction that yields the\n",
    "observed results from the first push, a total rotation of 1.5 rad."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "skilled-diving",
   "metadata": {},
   "outputs": [],
   "source": [
    "def error_func1(torque_friction, system):\n",
    "    force = system.force\n",
    "    results = run_two_phases(force, torque_friction, system)\n",
    "    theta_final = results.iloc[-1].theta\n",
    "    print(torque_friction, theta_final)\n",
    "    return theta_final - theta_test"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "generous-parcel",
   "metadata": {},
   "source": [
    "This error function takes torque due to friction as an input.\n",
    "It extracts `force` from the `System` object and runs the simulation.\n",
    "From the results, it extracts the last value of `theta` and returns the difference between the result of the simulation and the result of the experiment.\n",
    "When this difference is 0, the value of `torque_friction` is an estimate for the friction in the experiment.\n",
    "\n",
    "To bracket the root, we need one value that's too low and one that's too high.\n",
    "With `torque_friction=0.3`, the table rotates a bit too far:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "united-ranch",
   "metadata": {},
   "outputs": [],
   "source": [
    "guess1 = 0.3\n",
    "error_func1(guess1, system)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "heard-serial",
   "metadata": {},
   "source": [
    "With `torque_friction=0.4`, it doesn't go far enough."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "rotary-brazilian",
   "metadata": {},
   "outputs": [],
   "source": [
    "guess2 = 0.4\n",
    "error_func1(guess2, system)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "comparable-physiology",
   "metadata": {},
   "source": [
    "So we can use those two values as a bracket for `root_scalar`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "hungarian-cattle",
   "metadata": {},
   "outputs": [],
   "source": [
    "res = root_scalar(error_func1, system, bracket=[guess1, guess2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abandoned-remedy",
   "metadata": {},
   "source": [
    "The result is 0.333 N m, a little less than the initial guess."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "sorted-struggle",
   "metadata": {},
   "outputs": [],
   "source": [
    "actual_friction = res.root\n",
    "actual_friction"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "democratic-praise",
   "metadata": {},
   "source": [
    "Now that we know the torque due to friction, we can compute the force\n",
    "needed to rotate the turntable through the remaining angle, that is,\n",
    "from 1.5 rad to 3.14 rad.\n",
    "You'll have a chance to do that as an exercise, but first, let's animate the results."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "knowing-sleeve",
   "metadata": {},
   "source": [
    "## Animating the Turntable\n",
    "\n",
    "Here's a function that takes the state of the system and draws it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "funky-affect",
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib.patches import Circle\n",
    "from matplotlib.pyplot import gca, axis\n",
    "\n",
    "def draw_func(t, state):\n",
    "    theta, omega = state\n",
    "    \n",
    "    # draw a circle for the table\n",
    "    circle1 = Circle([0, 0], radius_disk)\n",
    "    gca().add_patch(circle1)\n",
    "    \n",
    "    # draw a circle for the teapot\n",
    "    center = pol2cart(theta, radius_pot)\n",
    "    circle2 = Circle(center, 0.05, color='C1')\n",
    "    gca().add_patch(circle2)\n",
    "\n",
    "    axis('equal')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dangerous-envelope",
   "metadata": {},
   "source": [
    "This function uses a few features we have not seen before, but you can read about them in the Matplotlib documentation.\n",
    "\n",
    "Here's what the initial condition looks like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "illegal-remainder",
   "metadata": {},
   "outputs": [],
   "source": [
    "state = results.iloc[0]\n",
    "draw_func(0, state)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efficient-summary",
   "metadata": {},
   "source": [
    "And here's how we call it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "toxic-shark",
   "metadata": {},
   "outputs": [],
   "source": [
    "# animate(results, draw_func)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "horizontal-shade",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "The example in this chapter demonstrates the concepts of torque, angular acceleration, and moment of inertia.\n",
    "We used these concepts to simulate a turntable, using a hypothetical observation to estimate torque due to friction.\n",
    "As an exercise, you can finish off the example, estimating the force needed to rotate the table to a given target angle.\n",
    "\n",
    "The next chapter describes several case studies you can work on to practice the tools from the last few chapters, including projectiles, rotating objects, `root_scalar`, and `maximize_scalar`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "pediatric-precipitation",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "You can access the notebooks at <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sixth-breach",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    " Continuing the example from this chapter, estimate the force that delivers the teapot to the desired position.\n",
    "Use this `System` object, with the friction we computed in the previous section."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "dental-density",
   "metadata": {},
   "outputs": [],
   "source": [
    "system3 = system.set(torque_friction=actual_friction)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "practical-cabinet",
   "metadata": {},
   "source": [
    "Write an error function that takes `force` and `system`, simulates the system, and returns the difference between `theta_final` and the remaining angle after the first push."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "grave-consent",
   "metadata": {},
   "outputs": [],
   "source": [
    "remaining_angle = theta_target - theta_test\n",
    "remaining_angle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hundred-judgment",
   "metadata": {},
   "source": [
    "Use your error function and `root_scalar` to find the force needed for the second push.\n",
    "Run the simulation with the force you computed and confirm that the table stops at the target angle after both pushes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "apparent-lancaster",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "persistent-rings",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "previous-pittsburgh",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "governing-component",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "statistical-behalf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "unauthorized-equity",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eight-prototype",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
